package com.tronsis.distribution.activity.me.upgrade;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.tronsis.distribution.R;
import com.tronsis.distribution.SysApplication;
import com.tronsis.distribution.bean.RegionBean;
import com.tronsis.distribution.bean.RulesMapBean;
import com.tronsis.distribution.bean.UserBean;
import com.tronsis.distribution.biz.factory.UpgradeBizFactory;
import com.tronsis.distribution.biz.factory.UserBizFactory;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.distribution.util.StateUtil;
import com.tronsis.distribution.widget.address.BottomDialog;
import com.tronsis.distribution.widget.address.OnAddressSelectedListener;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.util.StringUtil;
import com.tronsis.library.util.ToastUtil;
import com.tronsis.library.util.WindowUtil;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LevelApplySubmitActivity extends ToolBarBaseActivity {

    @BindView(R.id.tv_type)
    TextView mTvType;
    @BindView(R.id.ll_type)
    LinearLayout mLlType;
    @BindView(R.id.tv_level)
    TextView mTvLevel;
    @BindView(R.id.ll_level)
    LinearLayout mLlLevel;
    @BindView(R.id.ll_need_contribution)
    LinearLayout mLlNeedContribution;
    @BindView(R.id.ll_have_contribution)
    LinearLayout mLlHaveContribution;
    @BindView(R.id.tv_need_contribution)
    TextView mTvNeedContribution;
    @BindView(R.id.tv_have_contribution)
    TextView mTvHaveContribution;
    @BindView(R.id.tv_region)
    TextView mTvRegion;
    @BindView(R.id.btn_submit_apply)
    Button mBtnSubmitApply;
    @BindView(R.id.ll_region)
    LinearLayout mLlRegion;
    @BindView(R.id.tv_rule_tag)
    TextView mTvRuleTag;
    @BindView(R.id.tv_rule)
    TextView mTvRule;
    @BindView(R.id.iv_more1)
    ImageView mIvMore1;
    @BindView(R.id.iv_more2)
    ImageView mIvMore2;

    private PopupWindow mTypePopupWindow;
    private PopupWindow mAgentLevelPopupWindow;
    private PopupWindow mRegionPopupWindow;

    private String mLevel; //用户等级[B(), C(), D(), E()]
    private String mRegion;
    private String mType;  //[UPGRADE(升级), DEGRADE(降级), TO_AGENT(转代理)]

    private List<RegionBean> mRegionBeanList;

    private String mIntentType;
    private String mUserRole;
    private String mUserLevel;
    private Double needContribution;
    private Double haveContribution;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_level_apply_submit);
        ButterKnife.bind(this);
        setTitle(true, getString(R.string.apply));

        mRegionBeanList = SysApplication.getRegionList();
        mIntentType = getIntent().getType();

        RulesMapBean rulesMapBean = CommonUtil.getRulesMap(this);
        if (rulesMapBean != null && rulesMapBean.getRULE_UPGRADE() != null) {
            if (StringUtil.isEquals(mIntentType, "level")) {
                mTvRule.setText(rulesMapBean.getRULE_UPGRADE());
            } else if (StringUtil.isEquals(mIntentType, "switch")) {
                mLlType.setVisibility(View.GONE);
                mTvRule.setText(rulesMapBean.getRULE_TO_AGENT());
            }

        }

        UserBean loginUser = UserBizFactory.createBiz().getLoginUser(mContext);
        mUserRole = loginUser.getRole();
        mUserLevel = loginUser.getLevel();
        setView();
        httpGetUserInfo();
    }

    private void setView() {
        mTvType.setText("");
        mIvMore1.setVisibility(View.GONE);
        mLlType.setEnabled(false);
        if (StringUtil.isEquals(mIntentType, "switch")) {
            mTvType.setText("转代理");
            mType = StateUtil.TO_AGENT;
        } else {
            if (StringUtil.isEquals(mUserRole, StateUtil.ROLE_UO_AGENT)) {
                mTvType.setText("降级");
                mType = StateUtil.DEGRADE;
            } else {
                if (StringUtil.isEquals(mUserLevel, "B")) {
                    mTvType.setText("降级");
                    mType = StateUtil.DEGRADE;
                } else if (StringUtil.isEquals(mUserLevel, "E")) {
                    mTvType.setText("升级");
                    mType = StateUtil.UPGRADE;
                } else {
                    mIvMore1.setVisibility(View.VISIBLE);
                    mLlType.setEnabled(true);
                }
            }
        }
    }


    @OnClick(R.id.ll_type)
    void clickLlType() {
        showUpDownPopupWindow();
    }

    @OnClick(R.id.ll_level)
    void clickLlLevel() {
        String type = mTvType.getText().toString();
        if (StringUtil.isBlank(type)) {
            ToastUtil.showMessage(this, "请选择申请类型");
            return;
        }
        showLevelPopupWindow();
    }

    @OnClick(R.id.ll_region)
    void clickLlRegion() {
        String type = mTvType.getText().toString();
        if (StringUtil.isBlank(type)) {
            ToastUtil.showMessage(this, "请选择申请类型");
            return;
        }

        String level = mTvLevel.getText().toString();
        if (StringUtil.isBlank(level)) {
            ToastUtil.showMessage(this, "请选择申请等级");
            return;
        }

        //        showRegionPopupWindow();

        final RegionBean regionBean = new RegionBean();
        regionBean.setChildren(mRegionBeanList);

        int regionLevel = 3;
        if (mLevel != null) {
            switch (mLevel) {
                case "B":
                    regionLevel = 1;
                    break;
                case "C":
                    regionLevel = 2;
                    break;
                case "D":
                case "E":
                    regionLevel = 3;
                    break;
            }
        }


        final BottomDialog dialog = new BottomDialog(this, regionBean, regionLevel);
        final int finalRegionLevel = regionLevel;
        dialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(RegionBean province, RegionBean city, RegionBean county, RegionBean street) {
                String s = (province == null ? "" : "" + province.getName()) + (city == null ? "" : "" + city.getName()) + (county == null ? "" :
                        "" + county.getName()) + (street == null ? "" : "" + street
                        .getName());
                mTvRegion.setText(s);
                switch (finalRegionLevel) {
                    case 1:
                        mRegion = province.getCode();
                        break;
                    case 2:
                        mRegion = city.getCode();
                        break;
                    case 3:
                        mRegion = county.getCode();
                        break;
                }
                dialog.dismiss();
            }
        });
        dialog.show();
        dialog.getCloseBtn().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    @OnClick(R.id.btn_submit_apply)
    void clickSubmitApply() {

        String type = mTvType.getText().toString();
        if (StringUtil.isBlank(type)) {
            ToastUtil.showMessage(this, "请选择申请类型");
            return;
        }

        String level = mTvLevel.getText().toString();
        if (StringUtil.isBlank(level)) {
            ToastUtil.showMessage(this, "请选择申请等级");
            return;
        }

        String region = mTvRegion.getText().toString();
        if (StringUtil.isBlank(region)) {
            ToastUtil.showMessage(this, "请选择归属地");
            return;
        }

        // Allen : 判断已有贡献值是否足够升级
        if(StringUtil.isEquals(mType, StateUtil.UPGRADE)){
            if (needContribution > haveContribution) {
                ToastUtil.showToastInCenter(mContext, "抱歉，您未达到升级所需贡献值");
                return;
            }
        }
        httpSubmitUpgrade(mLevel, mRegion, mType);
    }

    private void showUpDownPopupWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.popupwindow_up_down_level, null);
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);

        if (mTypePopupWindow == null) {
            mTypePopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            mTypePopupWindow.setFocusable(true);
            mTypePopupWindow.setOutsideTouchable(true);
            mTypePopupWindow.setAnimationStyle(R.style.AnimationBottomDialog);
            mTypePopupWindow.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    if (motionEvent.getAction() == MotionEvent.ACTION_OUTSIDE) {
                        mTypePopupWindow.dismiss();
                        return true;
                    }
                    return false;
                }
            });

            view.findViewById(R.id.tv_switch_agent).setVisibility(View.GONE);//不用选择转代理

            view.findViewById(R.id.tv_up).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mTypePopupWindow.dismiss();
                    mType = StateUtil.UPGRADE;
                    mTvType.setText("升级");
                    mLevel = null;
                    mTvLevel.setText(null);
                }
            });

            view.findViewById(R.id.tv_down).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mTypePopupWindow.dismiss();
                    mType = StateUtil.DEGRADE;
                    mTvType.setText("降级");
                    mLevel = null;
                    mTvLevel.setText(null);
                    mLlHaveContribution.setVisibility(View.GONE);
                    mLlNeedContribution.setVisibility(View.GONE);
                }
            });

            view.findViewById(R.id.tv_switch_agent).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mTypePopupWindow.dismiss();
                    mType = StateUtil.TO_AGENT;
                    mTvType.setText("转代理");
                    mLlHaveContribution.setVisibility(View.GONE);
                    mLlNeedContribution.setVisibility(View.GONE);
                }
            });

            mTypePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowUtil.setPopWindowBackgroundAlpha(LevelApplySubmitActivity.this, 1f);
                }
            });
            view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mTypePopupWindow.dismiss();
                }
            });


        }
        WindowUtil.setPopWindowBackgroundAlpha(LevelApplySubmitActivity.this, 0.7f);
        mTypePopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    private void showLevelPopupWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.popupwindow_agent_level, null);
        // 强制隐藏键盘
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        mAgentLevelPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mAgentLevelPopupWindow.setFocusable(true);
        mAgentLevelPopupWindow.setOutsideTouchable(true);
        /* mAgentLevelPopupWindow.setBackgroundDrawable(new BitmapDrawable());*/
        mAgentLevelPopupWindow.setAnimationStyle(R.style.AnimationBottomDialog);
        mAgentLevelPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    mAgentLevelPopupWindow.dismiss();
                    return true;
                }
                return false;
            }
        });
        mAgentLevelPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowUtil.setPopWindowBackgroundAlpha(LevelApplySubmitActivity.this, 1f);
            }
        });


        if (StringUtil.isEquals(mType, StateUtil.UPGRADE)) {
            //升级
            switch (mUserLevel) {
                case "B":
                    view.findViewById(R.id.tv_b).setVisibility(View.GONE);
                    view.findViewById(R.id.tv_c).setVisibility(View.GONE);
                    view.findViewById(R.id.tv_d).setVisibility(View.GONE);
                    view.findViewById(R.id.tv_e).setVisibility(View.GONE);
                    break;
                case "C":
                    view.findViewById(R.id.tv_b).setVisibility(View.VISIBLE);
                    view.findViewById(R.id.tv_c).setVisibility(View.GONE);
                    view.findViewById(R.id.tv_d).setVisibility(View.GONE);
                    view.findViewById(R.id.tv_e).setVisibility(View.GONE);
                    break;
                case "D":
                    view.findViewById(R.id.tv_b).setVisibility(View.VISIBLE);
                    view.findViewById(R.id.tv_c).setVisibility(View.VISIBLE);
                    view.findViewById(R.id.tv_d).setVisibility(View.GONE);
                    view.findViewById(R.id.tv_e).setVisibility(View.GONE);
                    break;
                case "E":
                    view.findViewById(R.id.tv_b).setVisibility(View.VISIBLE);
                    view.findViewById(R.id.tv_c).setVisibility(View.VISIBLE);
                    view.findViewById(R.id.tv_d).setVisibility(View.VISIBLE);
                    view.findViewById(R.id.tv_e).setVisibility(View.GONE);
                    break;

            }
        }

        if (StringUtil.isEquals(mType, StateUtil.DEGRADE)) {
            //降级
            switch (mUserLevel) {
                case "B":
                    view.findViewById(R.id.tv_b).setVisibility(View.GONE);
                    view.findViewById(R.id.tv_c).setVisibility(View.VISIBLE);
                    view.findViewById(R.id.tv_d).setVisibility(View.VISIBLE);
                    if (StringUtil.isEquals(mUserRole, StateUtil.ROLE_UO_AGENT)) {
                        view.findViewById(R.id.tv_e).setVisibility(View.GONE);
                    } else {
                        view.findViewById(R.id.tv_e).setVisibility(View.GONE);
                    }
                    break;
                case "C":
                    view.findViewById(R.id.tv_b).setVisibility(View.GONE);
                    view.findViewById(R.id.tv_c).setVisibility(View.GONE);
                    view.findViewById(R.id.tv_d).setVisibility(View.VISIBLE);
                    if (StringUtil.isEquals(mUserRole, StateUtil.ROLE_UO_AGENT)) {
                        view.findViewById(R.id.tv_e).setVisibility(View.GONE);
                    } else {
                        view.findViewById(R.id.tv_e).setVisibility(View.GONE);
                    }
                    break;
                case "D":
                    view.findViewById(R.id.tv_b).setVisibility(View.GONE);
                    view.findViewById(R.id.tv_c).setVisibility(View.GONE);
                    view.findViewById(R.id.tv_d).setVisibility(View.GONE);
                    if (StringUtil.isEquals(mUserRole, StateUtil.ROLE_UO_AGENT)) {
                        view.findViewById(R.id.tv_e).setVisibility(View.GONE);
                    } else {
                        view.findViewById(R.id.tv_e).setVisibility(View.GONE);
                    }
                    break;
                case "E":
                    view.findViewById(R.id.tv_b).setVisibility(View.GONE);
                    view.findViewById(R.id.tv_c).setVisibility(View.GONE);
                    view.findViewById(R.id.tv_d).setVisibility(View.GONE);
                    view.findViewById(R.id.tv_e).setVisibility(View.GONE);
                    break;
            }
        }

        if (StringUtil.isEquals(mType, StateUtil.TO_AGENT)) {
            //转代理
            view.findViewById(R.id.tv_b).setVisibility(View.VISIBLE);
            view.findViewById(R.id.tv_c).setVisibility(View.VISIBLE);
            view.findViewById(R.id.tv_d).setVisibility(View.VISIBLE);
            if (StringUtil.isEquals(mType, StateUtil.DEGRADE)) {
                view.findViewById(R.id.tv_e).setVisibility(View.GONE);
            } else {
                view.findViewById(R.id.tv_e).setVisibility(View.GONE);
            }
        }

/*        if (StringUtil.isEquals(mUserRole, StateUtil.ROLE_UO_AGENT)) {
            view.findViewById(R.id.tv_e).setVisibility(View.GONE);
        }*/

        view.findViewById(R.id.tv_b).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setLevel("B");
            }
        });
        view.findViewById(R.id.tv_c).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setLevel("C");
            }
        });
        view.findViewById(R.id.tv_d).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setLevel("D");
            }
        });
        view.findViewById(R.id.tv_e).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setLevel("E");
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAgentLevelPopupWindow.dismiss();
            }
        });

        WindowUtil.setPopWindowBackgroundAlpha(LevelApplySubmitActivity.this, 0.7f);
        mAgentLevelPopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    private void setLevel(String selectLevel) {
        mAgentLevelPopupWindow.dismiss();
        if (!StringUtil.isEquals(mLevel, selectLevel)) {
            mRegion = null;
            mTvRegion.setText(null);
        }
        mLevel = selectLevel;
        mTvLevel.setText(StateUtil.getLevelText(mLevel));
        if(StringUtil.isEquals(mType, StateUtil.UPGRADE)){
            httpGetAskcontr(mLevel);
        }
    }


    private void httpSubmitUpgrade(String level, String region, String type) {
        if (region.length() < 6) {
            StringBuilder regionBuilder = new StringBuilder(region);
            for (int i = 0; i < (6 - region.length()); i++) {
                regionBuilder.append("0");
            }
            region = regionBuilder.toString();
        }
        try {

            UpgradeBizFactory.createBiz().submitUpgradeApply(this, level, region, type, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    setResult(Activity.RESULT_OK);
                    finish();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
        }

    }

    private void httpGetUserInfo() {
        try {
            UserBizFactory.createBiz().getUserInfo(this, new UICallBack() {
                @Override
                public void onStart() {

                }

                @Override
                public void onRefresh(Object data) {
                    UserBean bean = (UserBean) data;
                    if (data != null) {
                        mUserRole = bean.getRole();
                        mUserLevel = bean.getLevel();
                        setView();
                    }
                }

                @Override
                public void onFailure(int status) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //Allen: 获取升级所需贡献值
    private void httpGetAskcontr(String mUserLevel) {
        try {
            UpgradeBizFactory.createBiz().getAskcontr(this, mUserLevel, new UICallBack() {
                @Override
                public void onStart() {

                }

                @Override
                public void onRefresh(Object data) {
                    Double[] contr = (Double[]) data;
                    needContribution = contr[0];
                    haveContribution = contr[1];
                    mLlHaveContribution.setVisibility(View.VISIBLE);
                    mLlNeedContribution.setVisibility(View.VISIBLE);
                    mTvHaveContribution.setText(haveContribution+"");
                    mTvNeedContribution.setText(needContribution+"");
                }

                @Override
                public void onFailure(int status) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}